/**
 *
 */
package org.yabam.action;

import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.LocalizableMessage;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.ValidationMethod;

import org.yabam.model.Owner;
import org.yabam.util.StringUtil;

/**
 * @author brlau69n
 *
 */
public class RegisterAction extends YabamActionBean {

	//
	@ValidateNestedProperties({
        @Validate(field="login", required=true, minlength=5, maxlength=20),
        @Validate(field="name", required=true, minlength=5, maxlength=20),
        @Validate(field="password", maxlength=50, expression="this == passwordVerify"),
        @Validate(field="emailAddress", maxlength=50, mask="[\\w\\.]+@[\\w\\.]+\\.\\w+")
	})
	private Owner owner;

	@Validate(minlength=5, maxlength=50, expression="this == owner.password")
	private String passwordVerify;

	@ValidationMethod
	public void checkOwnerLoginAvaliability(ValidationErrors errors) {
		if (Owner.get(owner.getLogin())!=null) {
			errors.add("owner.login", new LocalizableError("register.owner.username.alreadyExists"));
		}
	}

	public Resolution register() {
		Owner newOwner = new Owner(owner.getLogin(), owner.getName(), owner.getEmailAddress(), owner.getPassword());
		newOwner.saveOrUpdate();
		getContext().getMessages().add( new LocalizableMessage("register.owner.success", newOwner.getLogin()));
		if ( StringUtil.empty(newOwner.getPassword())) {
			getContext().getMessages().add( new LocalizableMessage("register.owner.wontConnect", newOwner.getLogin()));
		}
		return new ForwardResolution("/");
	}

	/**
	 * @return the owner
	 */
	public Owner getOwner() {
		return owner;
	}

	/**
	 * @param owner the owner to set
	 */
	public void setOwner(Owner owner) {
		this.owner = owner;
	}

	/**
	 * @return the passwordVerify
	 */
	public String getPasswordVerify() {
		return passwordVerify;
	}

	/**
	 * @param passwordVerify the passwordVerify to set
	 */
	public void setPasswordVerify(String passwordVerify) {
		this.passwordVerify = passwordVerify;
	}

}
